<template>
  <el-drawer
    ref="drawerBox"
    v-bind="$attrs"
    :wrapper-closable="true"
    :close-on-press-escape="false"
    :size="showMobilePage?'100%':'80%'"
    title="选择达人审批"
    append-to-body
    v-on="$listeners"
  >
    <div class="drawer-content">
      <filter-input
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        line-feed
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
      />
      <el-tabs v-model="curTabName" type="card" class="contract-detail-tabs-container" style="margin: 8px 0px" @tab-click="onSubActiveOrderChange">
        <el-tab-pane :label="isShowOther?'可见签约':'签约列表'" name="all"/>
        <el-tab-pane v-if="isShowOther" name="other">
          <div slot="label">
            <span>不可见签约</span>
            <el-tooltip :open-delay="800" placement="top" effect="dark">
              <div slot="content" style="max-width: 210px">可通过创建人、审批人操作抄送后可见</div>
              <tipIcon is-diy style="position:relative;top:2px;"/>
            </el-tooltip>
          </div>
        </el-tab-pane>
        <el-tab-pane v-if="!hideSelectTab" name="selected">
          <span slot="label">已选择签约<el-badge v-if="selectedData.length" :value="selectedData.length" /></span>
        </el-tab-pane>
      </el-tabs>
      <div :style="multiple?'':{marginTop: '17px'}" class="table-list">
        <div v-loading="listLoading">
          <template v-if="(isAllTab && list.items.length > 0) || (isOtherTab && otherList.length) || (isSelectedTab && selectedData.length > 0)">
            <u-table
              ref="legalTableRef"
              :data="isAllTab?list.items:(isOtherTab?otherList:selectedTableData)"
              :row-class-name="(data) => tableRowClassName(data)"
              :height="setTableHeight"
              :border="true"
              class="fb-table"
              beautify-table
              header-drag-style
              header-cell-class-name="order-data-header-cell"
              element-loading-text="加载中..."
              empty-text="暂无数据"
              fit
              select-callback
              hightlight-current-rowref="tableRef"
              @sort-change="sortMethod"
              @select="selectTable"
              @select-all="selectTable">
              <u-table-column
                v-if="multiple"
                fixed="left"
                align="center"
                type="selection"
                width="50"
              />
              <u-table-column v-else align="left" label="" min-width="50">
                <template slot-scope="scope">
                  <el-radio v-model="singleSelectId" :label="scope.row.id" @change="changeRadio($event, scope.row)"><span/></el-radio>
                </template>
              </u-table-column>

              <u-table-column v-if="isAllTab" :min-width="handleTdWidth()" align="left" label="审批单号" label-class-name="diy-cell" class-name="diy-cell">
                <template slot-scope="scope" slot="header">
                  <div class="diyHeader">{{ scope.column.label }}</div>
                </template>
                <template slot-scope="scope">
                  <processSn :is-expedited="scope.row.isExpedited">
                    <div v-if="scope.row.signUpNum" style="cursor:pointer;color:#406EFF;" @click="toDetail(scope.row)">
                      <ToolTip :content="handleSnNumber(scope.row.signUpNum)" />
                    </div>
                    <div v-else>--</div>
                  </processSn>
                </template>
              </u-table-column>
              <u-table-column v-else align="left" label="审批单号" min-width="170">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.signUpNum" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="账号名称" min-width="110">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.accountNames" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="供应商名称" min-width="110">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.supplier" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="签单签约经纪">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.agentName" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="签约日期" min-width="160">
                <template slot-scope="scope">
                  <ToolTip :content="format(scope.row.signDate,'YYYY/MM/DD')" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="状态">
                <template slot-scope="scope">
                  <StatusText
                    v-if="scope.row.status || scope.row.status===0"
                    :color="['#FFBC3D','#FD8546', '#FF4E5F', '#999', '#31CC9C','#406EFF'][scope.row.status]"
                    :text="scope.row.status | signUpStatus"
                  />
                  <div v-else>--</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="当前节点">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.currentNode" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="当前处理人" min-width="110">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.proposer" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="所属部门" min-width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.departmentName" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="创建人">
                <template slot-scope="scope">
                  <CheckUserInfo :user-id="scope.row.creatorId" :label="scope.row.createUser" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="创建时间" min-width="160">
                <template slot-scope="scope">
                  <ToolTip :content="format(scope.row.createTime,'YYYY/MM/DD HH:mm:ss')" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="签约状态" min-width="150">
                <template slot-scope="scope">
                  <el-tooltip v-if="scope.row.signStatus" :open-delay="800" class="sign-status-tooltip" placement="top">
                    <div slot="content" class="tooltip-content">
                      <div
                        v-for="(item, index) in (scope.row.signStatusMapAccounts || [])"
                        :key="index"
                        class="account-item-tip"> {{ `${item.accountName}(${item.status})` }} <br></div>
                    </div>
                    <div style="font-size: 14px" class="ellipsisOne">{{ scope.row.signStatus }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="到期时长" width="150">
                <template slot-scope="scope">
                  <div v-if="scope.row.signDetailStatus === SIGN_DETAIL_STATUS.WAIT_SIGN">无合同</div>
                  <div v-else-if="scope.row.signDetailStatus === SIGN_DETAIL_STATUS.AUTO_RENEWAL">无新合同</div>
                  <div v-else-if="scope.row.isExpired" style="color: #FF4E5F">已到期</div>
                  <div v-else-if="scope.row.expiredDuration || scope.row.expiredDuration === 0">
                    距离到期日：<span :style="expiredTypeClass(scope.row.expiredDuration)">
                    {{ scope.row.expiredDuration !== 9999 ? scope.row.expiredDuration : '--' }}</span> 天</div>
                  <span v-else>距离到期日：-- 天</span>
                </template>
              </u-table-column>
            </u-table>
          </template>
          <div v-else style="margin-bottom: 24px;text-align: center;">
            <empty-placeholder :text="emptyText" />
            <span v-if="isAllTab && isShowOther">智能提示：切换至【不可见签约】可搜索无权限查看的签约噢~</span>
          </div>
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-if="isAllTab"
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            :small="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
          <el-pagination
            v-if="curTabName == 'selected'"
            v-show="selectedData.length > 0"
            :current-page="selectedPage"
            :page-size="selectedPerPage"
            :total="selectedData.length"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            :small="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-row>
        <fixed-pagination v-if="isAllTab || isOtherTab" class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="(!multiple && !singleSelect.id )|| (multiple && !hasSeleted)" size="small" type="primary" class="related-btn" @click="confirmRelated">关联签约</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
            <div v-if="isOtherTab" class="tip">搜索他人签约最多展示10条</div>
          </div>
          <el-pagination
            v-if="!showMobilePage && isAllTab"
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="showMobilePage ? pageLayout : 'total, prev, pager, next, sizes, jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
        <fixed-pagination v-if="curTabName == 'selected'" class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="!hasSeleted" size="small" type="primary" class="related-btn" @click="confirmRelated">{{ confirmText }}</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
          </div>
          <el-pagination
            v-if="!showMobilePage"
            v-show="selectedData.length > 0"
            :current-page="selectedPage"
            :page-size="selectedPerPage"
            :total="selectedData.length"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="showMobilePage ? pageLayout : 'total, prev, pager, next, sizes, jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>

<script>
// api
import { signUpList } from '@/api/signUp';
import { getDepartmentAll } from '@/api/config';
// filter
import { energyStatus as signUpStatus, expeditedOptions } from '@/filters/status';
import { format } from '@/filters/date';
import { expiredTypeClass } from '@/views/signUp/components/status.js';
// utils
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import axios from 'axios';
import { mapState } from 'vuex';
import { SIGN_DETAIL_STATUS } from '@/utils/const/resouce';
// mixins
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
// components
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import FilterInput from '@/components/Tool/filter';

export default {
  name: 'RelatedSignUp',
  filters: {
    signUpStatus
  },
  components: {
    FilterInput,
    EmptyPlaceholder
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  props: {
    multiple: {
      type: Boolean,
      default: true
    },
    confirmText: {
      type: String,
      default: '关联签约'
    },
    isShowOther: {
      type: Boolean,
      default: false
    },
    hideSelectTab: {
      type: Boolean,
      default: false
    },
    expandParams: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      SIGN_DETAIL_STATUS,
      filterInput: {},
      otherFilterInput: {},
      singleSelect: {
        id: ''
      }, // 单选
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      },
      selectedPage: 1,
      selectedPerPage: 20,
      sortType: '',
      sortName: '',
      listLoading: false,
      idKey: 'id', // 多选框参数
      isUmyTable: true,
      tableRefName: 'legalTableRef',
      curTabName: 'all',
      deptTreeList: [],
      selectedData: [],
      otherList: [],
      updateId: null,
      cancelToken: null,
      status: [
        { value: 0, label: '草稿中' },
        { value: 1, label: '审批中' },
        { value: 2, label: '未过审' },
        { value: 3, label: '已作废' },
        { value: 4, label: '已完成' },
        { value: 5, label: '待提交' }
      ],
      accountSignStatusOptions: [
        { value: 0, label: '未签约' },
        { value: 1, label: '已签约（待签合同）' },
        { value: 2, label: '已签约（已签合同）' },
        { value: 3, label: '已解约（协商解约）' },
        { value: 4, label: '已解约（到期解约）' },
        { value: 5, label: '已签约（已续约）' },
        { value: 6, label: '已签约（自动续约）' }
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableOutsideHeight() {
      return this.showMobilePage ? 270 : 215;
    },
    isOtherTab() {
      return this.curTabName === 'other';
    },
    isAllTab() {
      return this.curTabName === 'all';
    },
    isSelectedTab() {
      return this.curTabName === 'selected';
    },
    hasSeleted() {
      return this.multipleSelectionAll.length > 0;
    },
    emptyText() {
      if (this.isAllTab) {
        return '找不到签约内审，请换个关键词搜索';
      } else if (this.isOtherTab) {
        return '搜索账号名称、审批单号等可查找他人签约';
      }
      return '暂无数据';
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'accountName', name: '账号名称', labelWidth: '100px', type: 'input' },
        { keyword: 'signUpNum', name: '审批单号', labelWidth: '100px', type: 'input' },
        { keyword: 'supplier', name: '供应商名称', labelWidth: '100px', type: 'input' },
        { keyword: 'agentName', name: '签单签约经纪', labelWidth: '100px', type: 'input' },
        { keyword: 'createUser', name: '创建人', labelWidth: '100px', type: 'input' },
        { keyword: 'currentNode', name: '当前节点', labelWidth: '100px', type: 'input' },
        { keyword: 'comment', name: '评论', type: 'input', labelWidth: '100px' },
        { keyword: 'approvalComment', name: '审批意见', type: 'input', labelWidth: '100px' },
        // 下拉
        { keyword: 'signDetailStatus', name: '签约状态', type: 'mulSelect', options: this.accountSignStatusOptions },
        { keyword: 'departmentId', name: '所属部门', type: 'cascaderSelect', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        // 日期
        { keyword: 'signDate', name: '签约日期', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    },
    selectedTableData() {
      return this.selectedData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    paramsObj: {
      get() {
        if (this.isOtherTab) return this.otherFilterInput;
        return this.filterInput;
      },
      set(data) {
        if (this.isOtherTab) {
          this.otherFilterInput = data;
        } else {
          this.filterInput = data;
        }
      }
    },
    singleSelectId: {
      get() {
        return this.singleSelect.id;
      },
      set(id) {
        //
      }
    }
  },
  methods: {
    format, expiredTypeClass,
    // 初始获取数据
    init(data) {
      this.curTabName = 'all';
      this.fetchData();
      this.queryDeptTreeList();
      this.singleSelect = data || {};
    },
    initSelectData(data = []) {
      this.selectedData = data;
      this.multipleSelectionAll = data;
    },
    update(id) {
      this.updateId = id;
      this.fetchData();
    },
    updateItem() {
      const item = this.list.items.filter(el => el.id === this.updateId)[0];
      this.$emit('updateItem', item);
      this.updateId = null;
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      if (this.curTabName === 'all') {
        this.fetchData();
      }
    },
    handleLimit(row) {
      if (!row.contractEffectEndDate && !row.contractEffectStartDate) {
        return '/';
      }
      return '-';
    },
    // fitter
    queryClick() {
      if (this.isSelectedTab) this.curTabName = 'all';
      if (this.isOtherTab) {
        for (const key of Object.keys(this.otherFilterInput)) {
          if (!this.otherFilterInput[key] && this.otherFilterInput[key] !== 0) {
            delete this.otherFilterInput[key];
          }
        }
        if (JSON.stringify(this.otherFilterInput) === '{}') {
          this.otherList = [];
          return;
        }
      }
      this.fetchData(true);
    },
    queryEmpty() {
      this.sortType = '';
      this.sortName = '';
      if (this.isOtherTab) {
        this.otherFilterInput = {};
      } else {
        this.filterInput = {};
      }
      this.queryClick();
    },
    // 翻页
    handleData(tableData) {
      return tableData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    handleSizeChange(val) {
      if (this.curTabName === 'all') {
        this.perPage = val;
        this.fetchData(true);
      } else if (this.isSelectedTab) {
        this.selectedPerPage = val;
        this.setSelectRow(this.selectedTableData);
      }
    },
    handleCurrentChange(toPage) {
      if (this.curTabName === 'all') {
        this.page = toPage;
        this.fetchData();
      } else if (this.isSelectedTab) {
        this.selectedPage = toPage;
        this.setSelectRow(this.selectedTableData);
      }
    },
    // 获取列表数据
    fetchData(reset = false) {
      try {
        if (reset) this.page = 1;
        this.listLoading = true;
        const params = JSON.parse(JSON.stringify(this.paramsObj));
        params.page = this.isOtherTab ? 1 : this.page;
        params.perPage = this.isOtherTab ? 10 : this.perPage;
        if (!this.isOtherTab) {
          params.sortName = this.sortName;
          params.sortType = this.sortType;
        }

        params.status = 4; // 只能关联已完成的
        params.isOther = this.isOtherTab;

        paramsRangeFormat([
          { attr: 'createTime', start: 'createStartTime', end: 'createEndTime', type: 'time' },
          { attr: 'signDate', start: 'signStartTime', end: 'signEndTime', type: 'time' }
        ], params);
        paramsAryToStr(['signDetailStatus'], params);
        if (this.cancelToken) this.cancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        this.cancelToken = source;
        if (this.expandParams) {
          Object.keys(this.expandParams).forEach(key => {
            params[key] = this.expandParams[key];
          });
        }
        signUpList(params, source.token).then(({ data }) => {
          if (this.isOtherTab) { this.otherList = data.items; } else { this.list = data; }
          if (this.updateId) {
            this.updateItem();
          }
          this.listLoading = false;
          if (!this.isSelectedTab) this.setSelectRow(data.items);
        }, () => {
          this.listLoading = false;
        }).catch(e => {
          console.error(e);
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 关联合同
    confirmRelated() {
      const data = this.multiple ? this.selectedData : this.singleSelect;
      this.$emit('confirmRelated', data);
    },
    changeRadio(e, data) {
      this.singleSelect = data;
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      if (data.paneName === 'all') {
        this.fetchData();
      } else if (data.paneName === 'other') {
        if (this.cancelToken) this.cancelToken.cancel('cancel');
        this.setSelectRow(this.otherList);
      }
      if (this.isSelectedTab) this.setSelectRow(this.selectedTableData);
    },
    // 保留数据
    tableSelectionChange(selection) {
      this.selectedData = selection;

      if (this.isSelectedTab) this.setSelectRow(this.selectedTableData);
    },
    // 申请部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    // 跳转合同详情
    toDetail(row) {
      const routeUrl = this.$router.resolve({
        name: 'signUpDetail',
        query: {
          signUpId: row.id,
          processId: row.processId,
          fromList: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    onBackClick() {
      this.$refs.drawerBox.closeDrawer();
    },
    setParams(key, val) {
      this.$set(this.paramsObj, key, val);
      this.init();
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 12px 0 24px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  display: flex;
  align-items: center;
  > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
}
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-drawer__body {
  overflow-y: auto;
  margin-bottom: 56px;
}
::v-deep .el-drawer__header>span{
  font-size: 16px;
}
::v-deep .el-badge__content{
  background: #FB5227;
}
::v-deep .el-badge__content{
  transform: translateY(5px);
}
.tip {
  color: #999;
  font-size: 13px;
  margin-left: 20px;;
}
.drawer-content {
  padding: 22px 24px 0;
  overflow-y: auto;
  .table-list {
    &::v-deep {
     .el-table__header {
        .el-checkbox__inner {
          position: relative;
          left: -2px;
        }
      }
    }
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
      flex:1;
      height: 32px;
      display: flex;
      align-items: center;
      .related-btn {
        margin-left: 20px;
        padding-left: 12px;
        padding-right: 12px;
      }
    }
    ::v-deep .pagination-flex {
      position: absolute;
      width: 100% !important;
    }
  }
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
.contract-detail-tabs-container {
  &::v-deep {
    .el-tabs__header  {
      margin-bottom: 0 !important;
      border-bottom: 1px solid #ddd;
      .el-tabs__nav {
        border: none !important;
        height: 32px !important;
      }
      .el-tabs__item {
        padding: 0 12px !important;
        height: 32px !important;
        line-height: 32px !important;
        margin-right: 8px;
        border: 1px solid #ddd;
        border-radius: 4px 4px 0px 0px;
        color: #333;
        background: #f7f8fa;
        font-size: 16px;
        &:last-child {
          margin-right: 0px;
        }
        &.is-active {
          border-bottom-color: #FFFFFF !important;
          font-weight: bold;
          background: #fff;
          color: #406eff;
        }
      }
    }
  }
}
</style>
